package com.ruoyi.inventory.util;

import java.math.BigDecimal;
import java.util.List;
import java.util.ArrayList;
import com.ruoyi.inventory.domain.TInvSessionItem;
import com.ruoyi.inventory.domain.TSpPart;
import com.ruoyi.inventory.domain.dto.InventoryItemDTO;
import com.ruoyi.inventory.mapper.TSpPartMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 盘点明细转换器
 * 
 * @author ruoyi
 * @date 2025-09-28
 */
@Component
public class InventoryItemConverter 
{
    @Autowired
    private TSpPartMapper tSpPartMapper;

    /**
     * TInvSessionItem转换为InventoryItemDTO
     */
    public InventoryItemDTO toDTO(TInvSessionItem item) 
    {
        if (item == null) {
            return null;
        }
        
        InventoryItemDTO dto = new InventoryItemDTO();
        dto.setId(item.getId());
        dto.setSessionId(item.getSessionId());
        dto.setPartNo(item.getPartNo());
        dto.setTheoreticalQty(item.getTheoreticalQty());
        dto.setActualQty(item.getActualQty());
        dto.setDiffQty(item.getDiffQty());
        
        // 计算盘盈盘亏
        if (item.getActualQty() != null && item.getTheoreticalQty() != null) {
            BigDecimal diff = item.getActualQty().subtract(item.getTheoreticalQty());
            if (diff.compareTo(BigDecimal.ZERO) > 0) {
                dto.setSurplusQty(diff);
                dto.setLossQty(BigDecimal.ZERO);
            } else {
                dto.setSurplusQty(BigDecimal.ZERO);
                dto.setLossQty(diff.abs());
            }
        }
        
        // 获取备件详细信息
        if (item.getPartNo() != null) {
            TSpPart part = tSpPartMapper.selectTSpPartByPartNo(item.getPartNo());
            if (part != null) {
                dto.setPartName(part.getName());
                dto.setSpecNo(part.getSpecNo());
                dto.setPartTypeCode(part.getPartTypeCode());
            }
        }
        
        return dto;
    }

    /**
     * TInvSessionItem列表转换为InventoryItemDTO列表
     */
    public List<InventoryItemDTO> toDTOList(List<TInvSessionItem> items) 
    {
        if (items == null) {
            return null;
        }
        
        List<InventoryItemDTO> dtoList = new ArrayList<>();
        for (TInvSessionItem item : items) {
            dtoList.add(toDTO(item));
        }
        
        return dtoList;
    }
}
